﻿using Castle.DynamicProxy;
using Serilog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Wlmy.Ids4.CoustomInterceptor
{
    public class ServiceSaveInterceptor : IInterceptor
    {
        private readonly ServiceSaveAsyncInterceptor _serviceSaveAsyncInterceptor;

        public ServiceSaveInterceptor(ServiceSaveAsyncInterceptor serviceSaveAsyncInterceptor)
        {
            _serviceSaveAsyncInterceptor = serviceSaveAsyncInterceptor;
        }
        public void Intercept(IInvocation invocation)
        {
            Log.Logger.Debug($"方法调用:{invocation.TargetType.Name}=>{invocation.Method.Name}");
            invocation.Proceed();
            _serviceSaveAsyncInterceptor.ToInterceptor().Intercept(invocation);
        }
    }
    public class ServiceSaveAsyncInterceptor : IAsyncInterceptor
    {
        public void InterceptAsynchronous(IInvocation invocation)
        {
            SaveChanges(invocation);
        }

        public void InterceptAsynchronous<TResult>(IInvocation invocation)
        {
            invocation.ReturnValue = InternalInterceptAsynchronous<TResult>(invocation);
        }

        public void InterceptSynchronous(IInvocation invocation)
        {
            invocation.ReturnValue = InternalInterceptAsynchronous(invocation);
        }
        private async Task<TResult> InternalInterceptAsynchronous<TResult>(IInvocation invocation)
        {
            //获取执行信息
            var taskResult = (Task<TResult>)invocation.ReturnValue;
            var result = await taskResult.ConfigureAwait(false);
            SaveChanges(invocation);
            return result;
        }
        private async Task InternalInterceptAsynchronous(IInvocation invocation)
        {
            var taskResult = (Task)invocation.ReturnValue;
            await taskResult.ConfigureAwait(false);
            SaveChanges(invocation);

        }
        private void SaveChanges(IInvocation invocation)
        {
            var obj = invocation.InvocationTarget as dynamic;
            obj.SaveChanges();
        }
    }
}
